package com.mr.cai.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mr.cai.main.R;
import com.mr.cai.main.activity.base.MrCaiBaseActivity;
import com.mr.cai.main.bean.MrCaiPublicStatusBean;
import com.mr.cai.main.httpApi.MrCaiHttpApi;
import com.mr.cai.main.parse.MrCaiPublicStatusBeanParse;
import com.mr.cai.main.utils.CommonCoreUtil;
import com.mr.cai.main.view.LineEditText;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by hai8108 on 16/2/9.
 */
public class ForgetPwdActivity extends MrCaiBaseActivity{
    private ProgressBar pb_loaing;
    private LineEditText mobileNumEt;
    private LineEditText msgCodeEt;
    private TextView msgCodeRequestTv;
    private TextView pwdResetNext;
    private Subscription stopMePlease;
    private Subscription registerCodeReqSub;
    private Subscription registerSubscription;
    private final int REQUEST_CODE_RESET_TIME = 99;
    public static void launchActivity (Activity activity) {
        Intent intent = new Intent(activity, ForgetPwdActivity.class);
        activity.startActivity(intent);
    }
    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd_layout);
        ((TextView)findViewById(R.id.top_view).findViewById(R.id.pub_top_mid)).setText(R.string
                .forget_pwd_title);
        CommonCoreUtil.setClickAction(findViewById(R.id.top_view).findViewById(R.id.pub_top_left)
                , new Action1() {
            @Override
            public void call (Object o) {
                finish();
            }
        });
        findView();
        setAction();
    }
    private void findView(){
        pb_loaing = (ProgressBar) findViewById(R.id.pb_loaing);
        mobileNumEt = (LineEditText) findViewById(R.id.register_mobile_num);
        msgCodeEt = (LineEditText) findViewById(R.id.register_auth_code);
        msgCodeRequestTv = (TextView) findViewById(R.id.register_auth_code_request);
        pwdResetNext = (TextView) findViewById(R.id.forget_pwd_next);
        msgCodeEt.setBottomLineColor(R.color.color_main_sub_white_gray);
    }
    private void setAction(){
        CommonCoreUtil.setClickAction(msgCodeRequestTv, new Action1() {
            @Override
            public void call (Object o) {
                if (CommonCoreUtil.judgeRegxEmailAndMobile(mobileNumEt.getEditableText().toString())) {
                    msgCodeRequestTv.setEnabled(false);
                    getRegisterCodeMsg(mobileNumEt.getEditableText().toString());
                    setRegisterCodeClickAction();
                }
            }
        });
        CommonCoreUtil.setClickAction(pwdResetNext, new Action1() {
            @Override
            public void call (Object o) {
                if (CommonCoreUtil.judgeRegxEmailAndMobile(mobileNumEt.getEditableText().toString())) {
                    String code = msgCodeEt.getEditableText().toString();
                    if (TextUtils.isEmpty(code)) {
                        CommonCoreUtil.showToast(R.string.register_code_is_null);
                        return;
                    }
                    {
                        requestForgetPwd(mobileNumEt.getEditableText().toString(),
                                msgCodeEt.getEditableText().toString());
                    }
                }
            }
        });
    }
    private void setRegisterCodeClickAction () {
        stopMePlease = Observable.interval(1, TimeUnit.SECONDS).take(REQUEST_CODE_RESET_TIME)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted () {
                        if (stopMePlease.isUnsubscribed()) {
                            stopMePlease.unsubscribe();
                        }
                        msgCodeRequestTv.setEnabled(true);
                        msgCodeRequestTv.setText(R.string.register_auth_code_reset);
                    }
                    @Override
                    public void onError (Throwable e) {
                    }
                    @Override
                    public void onNext (Long number) {
                        msgCodeRequestTv.setText("\t" + (REQUEST_CODE_RESET_TIME - number
                                .intValue()) + " S " + "\t");
                    }
                });
    }

    private void getRegisterCodeMsg (String mobileNum) {
        Observable<MrCaiPublicStatusBean> authCodeObservable = MrCaiHttpApi.requestAuthcode
                (mobileNum, new MrCaiPublicStatusBeanParse());
        registerCodeReqSub = authCodeObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MrCaiPublicStatusBean>() {
                    @Override
                    public void onStart () {
                        CommonCoreUtil.showToast(R.string.request_code_send_txt);
                    }

                    @Override
                    public void onCompleted () {
                    }

                    @Override
                    public void onError (Throwable e) {
                        CommonCoreUtil.showToast(R.string.request_code_send_error);
                        msgCodeRequestTv.setEnabled(true);
                        msgCodeRequestTv.setText(R.string.register_auth_code_reset);
                    }

                    @Override
                    public void onNext (MrCaiPublicStatusBean mMrCaiPublicStatusBean) {
                        if (mMrCaiPublicStatusBean != null) {
                            if (!TextUtils.isEmpty(mMrCaiPublicStatusBean.getAuthCode())) {
                                msgCodeEt.setText(mMrCaiPublicStatusBean.getAuthCode());
                            } else {
                                CommonCoreUtil.showToast(mMrCaiPublicStatusBean.getMsg());
                            }
                        }
                    }
                });
    }
    private void requestForgetPwd (final String mobileNum, final String authCode) {
        Observable<MrCaiPublicStatusBean> authCodeObservable = MrCaiHttpApi.requestMsgCode
                (mobileNum, authCode, new MrCaiPublicStatusBeanParse());
        registerSubscription = authCodeObservable.observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call () {
                        pb_loaing.setVisibility(View.VISIBLE);
                    }
                })
                .subscribe(new Subscriber<MrCaiPublicStatusBean>() {
                    @Override
                    public void onCompleted () {
                        pb_loaing.setVisibility(View.GONE);
                    }
                    @Override
                    public void onError (Throwable e) {
                        pb_loaing.setVisibility(View.GONE);
                        CommonCoreUtil.showToast(R.string.data_request_fail);
                    }
                    @Override
                    public void onNext (MrCaiPublicStatusBean mMrCaiPublicStatusBean) {
                        if (mMrCaiPublicStatusBean != null && mMrCaiPublicStatusBean.isResult()
                                && mMrCaiPublicStatusBean.getCode() == 1) {
                            ResetPwdActivity.launchActivity(ForgetPwdActivity.this, mobileNum);
                            finish();
                        } else {
                            if (mMrCaiPublicStatusBean != null) {
                                CommonCoreUtil.showToast(mMrCaiPublicStatusBean.getMsg());
                            } else {
                                CommonCoreUtil.showToast(R.string.public_loading_net_err_txt);
                            }
                        }
                    }
                });
    }
    @Override
    protected void onDestroy () {
        super.onDestroy();
        CommonCoreUtil.hideSoftInput(mobileNumEt);
        CommonCoreUtil.hideSoftInput(msgCodeEt);
        if (registerCodeReqSub != null) {
            registerCodeReqSub.unsubscribe();
            registerCodeReqSub = null;
        }
        if (registerSubscription != null) {
            registerSubscription.unsubscribe();
            registerSubscription = null;
        }
        if (stopMePlease != null) {
            stopMePlease.unsubscribe();
            stopMePlease = null;
        }
    }

}
